package org.pizza.did.snowflake.listener;

import org.pizza.did.api.IdGenerator;
import org.pizza.did.api.WorkerIdDistributor;
import org.pizza.did.event.WorkIdChangeEvent;
import org.pizza.did.snowflake.SnowflakeIdGenerator;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.ApplicationListener;

/**
 * @author 高巍
 * @since 2020/11/26 4:52 下午
 */
@Slf4j
public class WorkIdChangeListener implements ApplicationListener<WorkIdChangeEvent> {

    public WorkIdChangeListener(WorkerIdDistributor workerIdDistributor, IdGenerator idGenerator) {
        this.workerIdDistributor = workerIdDistributor;
        this.idGenerator=idGenerator;
    }

    private WorkerIdDistributor workerIdDistributor;
    private IdGenerator idGenerator;

    @Override
    public void onApplicationEvent(WorkIdChangeEvent workIdChangeEvent) {
        if (idGenerator instanceof SnowflakeIdGenerator){
            ((SnowflakeIdGenerator)idGenerator).resetWorkerId(workerIdDistributor.distribute());
            log.info("发生WorkIdChangeEvent重置resetWorkerId成功，新workId：{}",((SnowflakeIdGenerator) idGenerator).getWorkerId());
        }
    }
}
